<template>
  <div class="innner-warp">
    <!--未接来电管理-->
    <div class="tiltle">{{$t('call.callLeakAdmin')}}</div>
    <div class="content-warp">
      <div class="content">
        <affix :label="$t('call.queryTerm')" class="serach-form-warp">
        </affix>
        <div class="serach-form">
          <el-form  :model="form" ref="form" label-position="top" label-width="80px">
            <el-row>
              <el-col :span="8">
                <el-form-item :label="$t('call.assginType')">
                  <el-select size="mini" v-model="form.ASSIGN_STATUS" :placeholder="$t('call.placeAssginType')">
                    <el-option :label="$t('public.all')" value=""></el-option>
                    <el-option :label="$t('call.assgin')" value="assigned"></el-option>
                    <el-option :label="$t('call.unassgin')" value="unassigned"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="$t('call.callLeakStatusType')"> <!--未接电话状态类型-->
                  <el-select size="mini" v-model="form.STATUS" :placeholder="$t('call.placeCallStatusType')">
                    <el-option :label="$t('public.all')" value=""></el-option>
                    <el-option label="IVR" value="leak"></el-option>
                    <el-option :label="$t('call.notDeal')" value="notDeal"></el-option>
                    <el-option :label="$t('call.queueLeak')" value="queueLeak"></el-option>
                    <el-option :label="$t('call.limit')" value="limit"></el-option>
                     <el-option :label="$t('monitor.InVoiceMail')" value="voicemail"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item class="line-input"  :label="$t('call.mainCall')">
                  <el-input size="mini" v-model.trim="form.CALL_NO" :placeholder="$t('call.placeMainCalle')"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item class="line-input" :label="$t('call.passiveCall')">
                  <el-input size="mini" :placeholder="$t('call.placePassiveCall')" v-model.trim="form.CALLED_NO"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="$t('call.skillsGrouop')">
                  <error-memo
                          ref="errorMemo"
                          :placeholder="$t('call.placeSkillsGrouop')"
                          :errorMemo="form.ERROR_MEMO"
                          @errorMemoChange
                                  ="getErrorMemoValue"
                          >
                  </error-memo>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="$t('call.callbackAgent')">
                  <agent-select
                          ref="agentSelect"
                          :multiple = "true"
                          :placeholder="$t('call.placeAgnet')"
                          :agent="form.CALLBACK_AGENT"
                          @agentChange="getAgentValue"
                          :noAll="true"
                          >
                  </agent-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="16">
                <el-form-item :label="$t('call.latelyLeakTime')">
                  <el-date-picker
                          v-model="offerintTime"
                          type="datetimerange"
                          size="mini"
                          :editable = "false"
                          @change = "getOfferintTime"
                          id="assginLeakSheet"
                          :placeholder="$t('call.choseTimeRange')">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item >
                <el-button type="primary" class="primary_btn" @click.stop="searchAssginTable()">{{$t('public.search2')}}</el-button>
                <el-button class="primary_btn report_excel_btn" @click.stop="cancel">{{$t('public.reset')}}</el-button>
              </el-form-item>
            </el-col>
          </el-row>
          </el-form>
        </div>
        <affix :label="$t('call.queryResult')" class="assgin-detail-warp">
        </affix>
        <div class="assgin-detail">
          <div class="detail-heard">
            <div class="btn-group" >
              <!--<span v-if="!isNotAll"></span>-->
              <div>
                <span v-show="$store.state.session.user.scope.call === 'all'" type="primary" class="distributionSelected" @click.stop="handlerAssgin"><a><i class="icon-fenpei iconfont"> </i> {{$t('call.assginCurrentChosedRecord')}}</a></span>
                <span v-show="$store.state.session.user.scope.call === 'all'" type="primary" @click.stop="handlerAssginAllocate"><a><i class="icon-fenpei iconfont assgin-query"> </i> {{$t('call.assginCurrentQueryRecord')}}</a></span>
                <span v-if="leakExport" type="primary" @click.stop="handlerExport"><a><i class="icon-daochu1 iconfont assgin-query"> </i> {{$t('public.export')}}</a></span>
                <!--<span  type="primary" class="primary_btn report_excel_btn delResult" @click.stop="confirmDelAllCdr"><a><i class="icon-shanchu iconfont assgin-query"> </i> {{$t('call.delCurrentResult')}}</a></span>-->
                <!--因为后台的未接管理和通话记录存的一张表，未接管理删除之后，通话记录也就删除了，此功能被砍  liyl 20180525-->
                <assgin-leak-sheet
                        :isAssignDialog = "isAssignDialog"
                        @cancelAndSubmit="assignDialogClose"
                        :ids="ids"
                        :count="checkedCount||allCountClone"
                        ></assgin-leak-sheet>
              </div>
            </div>
            <div class="pagination-warp">
              <pagination
                      :small="true"
                      :currentPage="currentPage"
                      :moreFlag="moreFlag"
                      :count="count"
                      :allCount="allCount"
                      :showCount="false"
                      @turnPage="turnPage"
                      :totalPage="totalPage"
                      @getAllCount ="getAllCount">
              </pagination>
            </div>
          </div>
          <div class="detail-body call-sheet-leak-body">
            <el-table
                    ref="multipleTable"
                    :data="tableData"
                    tooltip-effect="dark"
                    style="width: 100%"
                    size="mini"
                    @selection-change="handleSelectionChange">
              <el-table-column
                      type="selection"
                      width="55">
              </el-table-column>
              <el-table-column
                      prop="customerName"
                      :label="$t('call.custName')"
                      width="88">
              </el-table-column>
              <el-table-column
                      prop="callNo"
                      :label="$t('call.mainCallNum')"
                      show-overflow-tooltip>
              </el-table-column>
              <el-table-column
                      prop="newCalledNo"
                      :label="$t('call.passiveCallNum')"
                      show-overflow-tooltip>
              </el-table-column>
              <el-table-column
                      prop="assginType"
                      :label="$t('call.assginType')"
                      show-overflow-tooltip>
              </el-table-column>
              <el-table-column
                      prop="disposalAgent"
                      :label="$t('call.callStatusType')"
                      width="120"
                      show-overflow-tooltip>
                <template scope="scope">
                  <call-status
                          :status = "scope.row.status"
                          ></call-status>
                </template>
              </el-table-column>
              <el-table-column
                      :label="$t('call.lastOneCall')"
                      width="155">
                <template scope="scope">{{ scope.row.newOfferingTime }}</template>
              </el-table-column>
              <el-table-column
                  :label="$t('call.skillsGrouop')"
                  show-overflow-tooltip>
                <template scope="scope">{{ scope.row.QUEUE_NAME || '--' }}</template>
              </el-table-column>
              
              <el-table-column
                      :label="$t('call.OriginAttrAgent')"
                      width="155">
                <template scope="scope">{{ scope.row.OWNER_INFO}}</template>
              </el-table-column>
              <el-table-column
                      :label="$t('call.callbackAgent')"
                      width="155">
                <template scope="scope">{{ scope.row.callBackAgentName}}</template>
              </el-table-column>
              <el-table-column
                      :label="$t('public.operate')"
                      width="80">
                <template scope="scope">
                  <el-button type="text" @click.stop="handlerDetail(scope.row._id)">
                    {{$t('call.queryDetail')}}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>
    <leak-sheet-detai-dailog
      ref="openOrCloseDialog"
      :history = "history"
    >
    </leak-sheet-detai-dailog>
  </div>
</template>
<script>
  // 此组件是未接来电管理的列表 && 查询栏
  import Affix from '../../ui-modules/affix/Affix'
  import Pagination from '@/components/public-modules/card/Pagination'
  import AssginLeakSheet from './AssginLeakSheet'
  import LeakSheetDetaiDailog from './LeakSheetDetaiDailog'
  import ErrorMemo from '@/components/public-modules/cache/ErrorMemo.vue'
  import AgentSelect from '@/components/public-modules/cache/AgentSelect'
  import CallStatus from '@/components/public-modules/cache/CallStatus.vue'
  import CustomerOwnerSelect from '../customer/CustomerOwnerSelect.vue'
  import { deepClone, getFormatDateTime, isHasMenu } from '@/utils/m7Utils'

  export default {
    name: 'AssginLeakSheetDetail',
    data () {
      return {
        leakExport: false,
        qu: '',
        allCount: 0,
        allCountClone: 0,
        moreFlag: false,
        owner: 'NA',
        categoryId: 'NA',
        ids: [],
        initValue: 0,
        offerintTime: null,
        value: [],
        agents: [],
        // isDetailDialog: false,
        isAssignDialog: false,
        history: [],
        pages: 1,
        count: 0,
        currentPage: 1,
        checkedCount: 0,
        currentCheckBtn: '', // 当前操作的按钮 （分配选中的记录 or 分配查询到的记录）
        form: {
          ASSIGN_STATUS: '',
          STATUS: '',
          CALL_NO: '',
          CALLED_NO: '',
          ERROR_MEMO: [],
          CALLBACK_AGENT: [],
          OFFERING_TIME: null
        },
        tableData: []
      }
    },
    components: {
      Pagination,
      Affix,
      AssginLeakSheet,
      ErrorMemo,
      AgentSelect,
      CallStatus,
      CustomerOwnerSelect,
      LeakSheetDetaiDailog
    },
    computed: {
      totalPage () { // 共xx页
        return Math.ceil(this.count / 10)
      }
//      isNotAll () { // 这块的控制有问题，按照老板分配按钮只受通话的数据权限控制，不受客户的数据权限控制
//        let user = this.$store.state.session.user
//        let scope = user.scope.customer
//        return scope === 'all'
//      }
    },
    methods: {
      turnPage (val) { // 翻页
        this.currentPage = val
        this.searchAssginTable(val)
      },
      // confirmDelAllCdr () { // 删除所查询到的<!--因为后台的未接管理和通话记录存的一张表，未接管理删除之后，通话记录也就删除了，此功能被砍  liyl 20180525-->
      //   let respCount = ''
      //   if (this.moreFlag) {
      //     this.allCount = 0
      //     let form = this.qu
      //     form.queryCount = true
      //     this.checkedCount = null
      //     this.$store.dispatch('getCallSheetLeakTable', form).then((resp) => {
      //       delete form.queryCount
      //       // this.allCount = resp.count
      //       // this.moreFlag = false
      //       respCount = resp.count
      //       let data = deepClone(this.form)
      //       this.$confirm(this.$t('call.confirmDell', { count: respCount }), this.$t('public.tip'), {
      //         confirmButtonText: this.$t('public.confirm'),
      //         cancelButtonText: this.$t('public.cancel'),
      //         type: 'warning'
      //       }).then(() => {
      //         this.$store.dispatch('confirmDelAllCdr', data).then((resp) => {
      //           this.$message({
      //             type: 'success',
      //             message: this.$t('sms.successDel')
      //           })
      //           this.tableData = []
      //         })
      //       }).catch(() => {
      //         this.$message({
      //           type: 'info',
      //           message: this.$t('sms.cancelDel')
      //         })
      //       })
      //     })
      //   } else {
      //     let data = deepClone(this.form)
      //     respCount = this.count  // 少于20 没有more取保存值
      //     this.$confirm(this.$t('call.confirmDell', { count: respCount }), this.$t('public.tip'), {
      //       confirmButtonText: this.$t('public.confirm'),
      //       cancelButtonText: this.$t('public.cancel'),
      //       type: 'warning'
      //     }).then(() => {
      //       this.$store.dispatch('confirmDelAllCdr', data).then((resp) => {
      //         this.$message({
      //           type: 'success',
      //           message: this.$t('sms.successDel')
      //         })
      //         this.tableData = []
      //       })
      //     }).catch(() => {
      //       this.$message({
      //         type: 'info',
      //         message: this.$t('sms.cancelDel')
      //       })
      //     })
      //   }
      // },
      getAllCount () { // 获取所有count
        this.allCount = 0
        let form = this.qu
        form.queryCount = true
        this.$store.dispatch('getCallSheetLeakTable', form).then((resp) => {
          delete form.queryCount
          this.allCount = resp.count
          this.moreFlag = false
        })
      },
      historyClose () { // 查看详情弹窗
        this.$refs.openOrCloseDialog.openOrCloseDialog(false)
        // this.isDetailDialog = !this.isDetailDialog // 写法优化,(分配到自己身上之后点击浏览器提醒，会有遮罩体)
      },
      handlerDetail (_id) { // 点击查看详情
        this.$store.dispatch('showMissedCallInfo', {_id}).then(val => {
          this.history = val.list
          // this.isDetailDialog = !this.isDetailDialog
          this.$refs.openOrCloseDialog.openOrCloseDialog(true)
        })
      },
      handlerAssgin (val) { // 分配当前所选
        if (this.$store.state.checkedVal === 0) {
          // this.$message.warning(this.$t('call.placeLeakCallRecord'))
          this.checkedCount = 0
          // return
        } else if (this.$store.state.checkedVal > 0) {
          this.checkedCount = this.$store.state.checkedVal
        }
        if (this.checkedCount === 0) {
          this.$message.warning(this.$t('call.placeLeakCallRecord'))
          return
        }
        this.isAssignDialog = !this.isAssignDialog
        this.currentCheckBtn = 'assgin'
      },
      handlerAssginAllocate (val) { // 分配当前所查询的
        this.allCount = 0
        let form = this.qu
        form.queryCount = true
        this.checkedCount = null
        this.$store.dispatch('getCallSheetLeakTable', form).then((resp) => {
          delete form.queryCount
          this.allCountClone = resp.count
          if (resp.count < 1) {
            this.$message.warning(this.$t('call.noLeakCallRecord'))
            return
          }
          this.isAssignDialog = !this.isAssignDialog
          this.currentCheckBtn = 'assginAllocate'
        })
      },
      handleSelectionChange (val) {  // 选中的未接来电个数
        this.ids = val.map(val => {
          return val._id
        })
        this.checkedCount = val.length
        this.$store.state.checkedVal = val.length
      },
      getAgentValue (val) { // 回访坐席
        this.form.CALLBACK_AGENT = val
      },
      getErrorMemoValue (val) { // 技能组
        this.form.ERROR_MEMO = val
      },
      getOfferintTime (val) { // change最近未接时间
        if (val) {
          this.form.OFFERING_TIME = {
            $gte: getFormatDateTime(this.offerintTime[0]),
            $lte: getFormatDateTime(this.offerintTime[1])
          }
        } else {
          this.form.OFFERING_TIME = null
        }
      },
      searchAssginTable (page) {  // 点击搜索按钮
        let data = deepClone(this.form)
        data.page = page || 1
        data.pageSize = 10
        data.morePage = page >= this.pages ? Math.floor(page / this.pages + 1) : 1
        this.fetchData(data)
      },
      cancel () { // 重置
        this.$refs.errorMemo.value = ''
        this.$refs.agentSelect.value = ''
        this.$refs.form.resetFields()
        this.$set(this, 'form', {
          ASSIGN_STATUS: '',
          STATUS: '',
          CALL_NO: '',
          CALLED_NO: '',
          ERROR_MEMO: '',
          CALLBACK_AGENT: [],
          OFFERING_TIME: null
        })
        this.offerintTime = null
        this.initValue = Math.random()
        this.owner = 'NA'
        this.categoryId = 'NA'
        this.fetchData()
      },
      assignDialogClose (data) {  // 弹框内 点击保存的事件   点击X号关闭弹框也触发
        if (data.owners && data.owners.length === 0) {
          this.$message.warning(this.$t('call.placeChoseAgentToAssginType'))
          return
        }
        if (data.type === 'close' || data.type === 'cancel') {
          this.isAssignDialog = data.bool
          return
        }
        this.isAssignDialog = data.bool
        let agents = data.owners
        if (this.currentCheckBtn === 'assgin') { // 分配当前所选的
          let i = 0
          let j = 0
          let res = []
          for (i = 0; i < agents.length; i++) {
            for (j = 0; j < agents[i].count; j++) {
              let _id = ''
              _id = this.ids.pop()
              res.push({
                _id,
                CALLBACK_AGENT: agents[i].owner
              })
            }
          }
          this.$store.dispatch('assignMissedCall', res).then(val => {
            if (val && val.success) {
              this.searchAssginTable()
              this.$message.success(this.$t('call.assignSuccess'))
            }
          })
        } else { // 分配当前所查询的
          let agentArr = []
          let resData = {}
          for (let i = 0; i < agents.length; i++) {
            let obj = {'CALLBACK_AGENT': agents[i].owner, 'count': agents[i].count}
            agentArr.push(obj)
          }
          resData.assign = agentArr
          resData.query = this.form
          this.$store.dispatch('assignMatchedMissedCall', resData).then(resp => {
            if (resp && resp.success) {
              this.searchAssginTable()
              this.$message.success(this.$t('call.assignSuccess'))
            }
          })
        }
      },
      handlerExport () {
        if (this.count <= 0) {
          this.$message.error(this.$t('public.noData'))
          return
        }
        let data = deepClone(this.form)
        this.$store.dispatch('addMissedCDRExportTask', data).then(resp => {
          if (resp && resp.success) {
            this.$message.success(this.$t('call.callLeakExportWarn'))
          }
        })
      },
      fetchData (req) { // 查询列表数据
        this.allCount = 0
        this.moreFlag = false
        let data = {
          page: 1,
          morePage: 1,
          pageSize: 10
        }
        if (req) {
          data = req
        }
        this.$store.dispatch('getCallSheetLeakTable', data).then((resp) => {
          this.qu = data
          this.tableData = resp.tableData
          if (data.page === 1) {
            this.pages = resp.count / 10 || 1
          }
          if (resp.more) {
            this.moreFlag = true
          } else {
            this.moreFlag = false
          }
          this.count = resp.count
        })
      }
    },
//    beforeRouteLeave (to, from, next) {
//      this.$destroy()
//      next()
//    },
    beforeMount () {
      this.fetchData()
      if (isHasMenu('assign_missed_cdr_export_task', this.$store.state.session.user)) {
        this.leakExport = true
      }
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../assets/common.styl"
  .el-select
    width 194px
  .el-col-8
    .el-input
      width 194px
      font-size 12px
  .el-col-10
    width 194px
  .content-warp
    height calc(100vh - 92px)
    overflow auto
    .content
      padding 20px 20px 0
  .innner-warp
    .tiltle
      height 39px
      border-bottom 1px solid $c-border1
      color $cf-gray1
      font-size 14px
      line-height 39px
      padding-left 16px

    .serach-form
      .primary_btn
        float right
        &:first-child
          margin-left 15px
    .assgin-detail
      .detail-heard
        border 1px solid #dfe6ec
        border-bottom 0
        padding 4px
        display flex
        justify-content space-between
        align-items center
        .btn-group
          display inline-block
          .delResult
            margin-left: -13px
          .assgin-query
            margin-left 12px
          .distributionSelected
            margin-left: 11px
        .pagination-warp
          float right
</style>

